package com.hp.usage.gr.db;

import com.hp.siu.collector.rules.Rule;
import com.hp.siu.collector.rules.RuleException;
import com.hp.siu.logging.Level;
import com.hp.siu.logging.Logger;
import com.hp.siu.utils.*;
import com.hp.usage.gr.GrBaseRule;
import com.hp.usage.jdbc.poolservice.client.ConnectionPolicy;
import com.hp.usage.jdbc.poolservice.client.ConnectionPolicyHelper;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by huxiaoji on 1/18/2016.
 */
public abstract class DbBasedRule extends GrBaseRule {
    private static Logger log_ = Logger.getLogger("com.hp.usage.gr.db.DbBasedRule", "com.hp.usage.gr.message_catalog");

    private String connectionPoolID_;
    private String database_;
    private String databaseClass_;
    private String user_;
    private String password_;
    private int maxDatabaseConnections_;
    private int retryCount_;
    private int retryDelay_;

    protected ConnectionPolicy connectionPolicy = null;
    private JDBCConnectionFactory factory_;
    private ThreadLocal<Connection> dbLocal_;
    private ObjectPool dbPool_ = null;
    protected NormalizedMeteredEvent nme1;

    public abstract void applyRule(NormalizedMeteredEvent nme) throws RuleException;

    @Override
    public void applyRule(NormalizedMeteredEvent nme, NormalizedMeteredEvent normalizedMeteredEvent1) throws RuleException {
        this.nme1 = normalizedMeteredEvent1;
        applyRule(nme);

        if (this.next_ != null){
            this.next_.applyRule(nme, normalizedMeteredEvent1);
        }
    }

    protected Connection getConnection() throws SQLException {
        Connection conn = null;
        try {
            if (connectionPolicy != null) {
                conn = connectionPolicy.getConnection();
            } else if (dbPool_ != null) {
                conn = (Connection) dbPool_.getObject();
            } else {
                conn = dbLocal_.get();
                if (conn == null) {
                    conn = (Connection) factory_.create();
                    dbLocal_.set(conn);
                }
            }
            conn.setAutoCommit(false);
            return conn;
        } catch (Exception e){
            throw (SQLException) new SQLException(e.getMessage()).initCause(e);
        }
    }

    protected void releaseConnection(Connection conn)
    {
        if (this.connectionPolicy == null)
        {
            if (this.dbPool_ == null) {
                return;
            }
            if (log_.isLoggable(Level.DEBUG4)) {
                log_.logDebug4("Releasing the connection back to the connection pool");
            }
            this.dbPool_.releaseObject(conn);
        }
        else
        {
            try
            {
                conn.close();
            }
            catch (SQLException localSQLException)
            {
                log_.logException(Level.INFO, "JDBCSessionStoreMsg12", localSQLException);
            }
        }
    }

    /**
     * ConnectionPoolID
     * Database
     * DatabaseClass
     * User
     * Password
     *
     * @param config
     * @throws ConfigurationException
     */
    public void configure(Config config) throws ConfigurationException {
        if (log_.isLoggable(Level.DEBUG4)){
            log_.logDebug4("GrInitialization.configure()");
        }
        try {
            this.connectionPoolID_ = config.getAttribute("ConnectionPoolID");
            if (((this.connectionPolicy = ConnectionPolicyHelper.resolveConnectionPolicy(config)) != null) && (log_.isLoggable(Level.INFO))) {
                log_.logInfo("GrInitialization {0} will source its connections from the ConnectionPool {1} configured in JDBCConnectionPoolService.", new Object[]{config.getName(), this.connectionPoolID_});
            }
        } catch (Exception e){
            throw new ConfigurationException("JDBCConnection Policy is not found or is faulty :ConnectionPolicy" + e);
        }
        if (connectionPoolID_ == null){
            user_ = config.getAttribute("User");
            password_ = config.getAttribute("Password");
            database_ = config.getAttribute("Database");
            databaseClass_ = config.getAttribute("DatabaseClass");
            factory_ = new JDBCConnectionFactory(databaseClass_, database_, user_, password_);
            maxDatabaseConnections_ = config.getAttributeAsInt("MaxDatabaseConnections", 10);
            if (maxDatabaseConnections_ < 1) {
                this.dbLocal_ = new ThreadLocal();
            } else {
                this.dbPool_ = new ObjectPool(this.factory_, maxDatabaseConnections_);
            }
            this.retryCount_ = config.getAttributeAsInt("RetryCount", 1);
            if (log_.isLoggable(Level.DEBUG)) {
                log_.logDebug("Retry Count is " + this.retryCount_);
            }
            this.retryDelay_ = config.getAttributeAsInt("RetryDelay", 0);
            if (log_.isLoggable(Level.DEBUG)) {
                log_.logDebug("Retry Delay is  " + this.retryDelay_ + " seconds.");
            }
            this.retryDelay_ *= 1000;
        }
        else
        {
            this.retryCount_ = 0;
            this.retryDelay_ = 0;
        }
    }

    protected String getString(Map<String, Object> map, String key){
        Object obj = map.get(key);
        if (obj == null){
            return null;
        } else if (obj instanceof String){
            return (String)obj;
        } else {
            return obj.toString();
        }
    }

    protected int getInt(Map<String, Object> map, String key){
        Object obj = map.get(key);
        if (obj instanceof Number){
            return ((Number)obj).intValue();
        } else {
            return Integer.parseInt(obj.toString());
        }
    }

    protected void assertHasValue(Map<String, Object> map, String key) throws RuleException{
        Object obj = map.get(key);
        if (obj == null) throw new RuleException("Can't find mandatory field " + key);
    }

    protected void assertHasInt(Map<String, Object> map, String key) throws RuleException{
        assertHasValue(map, key);
        Object obj = map.get(key);
        if (!(obj instanceof Number)){
            try{
                Integer.parseInt(obj.toString());
            } catch (NumberFormatException e){
                throw new RuleException("The field " + key + " should be integer value.");
            }
        }
    }

    protected List<Map<String, Object>> getList(Map<String, Object> map, String key) throws RuleException{
        assertHasValue(map, key);
        return (List<Map<String, Object>>) map.get(key);
    }

    protected Map<String, Object> getMap(Map<String, Object> map, String key) throws RuleException{
        Object obj = map.get(key);
        if (obj == null) throw new RuleException("Can't find mandatory field " + key);
        return (Map<String, Object>) obj;
    }
}
